python 将字典的特殊字符转换成html 编码
urllib.quote
1
2
3
4
5
6
7
8
9In [16]: urllib.quote(json.dumps(a))
Out[16]: '%7B%22project%22%3A%20%22test%22%2C%20%22messge%22%3A%20%22mysql%20qps%20%3E300000%20is%20down%22%2C%20%22hostname%22%3A%20%22salve-02%22%2C%20%22alert_time%22%3A%20%222017.06.07%2014%3A17%3A25%22%2C%20%22value%22%3A%20%22500%22%7D'
In [17]: a
Out[17]:
{'alert_time': '2017.06.07 14:17:25',
'hostname': 'salve-02',
'messge': 'mysql qps >300000 is down',
'project': 'test',
'value': '500'}urllib.encode 只是将字典的键值对取出来作为url的参数和值的形式
1
2In [18]: urllib.urlencode(a)
Out[18]: 'project=test&messge=mysql+qps+%3E300000+is+down&hostname=salve-02&alert_time=2017.06.07+14%3A17%3A25&value=500'
python中数据结构中包含有unicode编码的字符串
可以使用json.dumps
1
2
3
4
5
6
7
8
9
10
11In [16]: a={'1': u'你好'}
In [17]: print a
{'1': u'\u4f60\u597d'}
In [18]: import json
In [19]: print json.dumps(a, indent=4)
{
"1": "\u4f60\u597d"
}对list的类型,可以使用join方法
1
2
3
4
5
6
7
8
9
10
11
12In [20]: a = [u'a', u'b', u'c']
In [21]: print a
[u'a', u'b', u'c']
In [22]: ",".join(a)
Out[22]: u'a,b,c'
In [23]: c = ",".join(a)
In [24]: print c
a,b,c单个字符串可以直接用replace替换